/**
 * Copyright © 2016-2021 The Thingsboard Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.iot.queue.rabbitMq;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.util.Base64;
import com.example.iot.entity.id.EntityIdFactory;
import com.example.iot.entity.id.EntityType;
import com.example.iot.entity.id.RuleChainId;
import com.example.iot.msg.QueueToRuleEngineMsg;
import com.example.iot.msg.TbMsg;
import com.example.iot.msg.TbMsgMetaData;
import com.example.iot.queue.QueueCallback;
import com.example.iot.queue.QueueProducer;
import com.example.iot.queue.TopicPartitionInfo;
import com.example.iot.queue.message.DefaultQueueMsg;
import com.example.iot.queue.message.ProtoQueueMsg;
import com.example.iot.queue.message.QueueMsg;
import com.example.iot.queue.message.RuleEngineQueueMsg;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;

@Slf4j
public class TbRabbitMqProducerTemplate<T extends QueueMsg> implements QueueProducer<T> {
    private final String defaultTopic;
    private final TbRabbitMqAdmin admin;
    private final TbRabbitMqSettings rabbitMqSettings;
    private final ListeningExecutorService producerExecutor;
    private final Channel channel;
    private final Connection connection;

    private final Set<TopicPartitionInfo> topics = ConcurrentHashMap.newKeySet();

    public TbRabbitMqProducerTemplate(TbRabbitMqAdmin admin, TbRabbitMqSettings rabbitMqSettings, String defaultTopic) {
        this.admin = admin;
        this.defaultTopic = defaultTopic;
        this.rabbitMqSettings = rabbitMqSettings;
        producerExecutor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
        try {
            connection = rabbitMqSettings.getConnectionFactory().newConnection();
        } catch (IOException | TimeoutException e) {
            log.error("Failed to create connection.", e);
            throw new RuntimeException("Failed to create connection.", e);
        }

        try {
            channel = connection.createChannel();
        } catch (IOException e) {
            log.error("Failed to create chanel.", e);
            throw new RuntimeException("Failed to create chanel.", e);
        }
    }

    @Override
    public void init() {

    }

    @Override
    public String getDefaultTopic() {
        return defaultTopic;
    }

    @Override
    public void send(TopicPartitionInfo tpi, T msg, QueueCallback callback) {
        createTopicIfNotExist(tpi);
        AMQP.BasicProperties properties = new AMQP.BasicProperties();
        try {
            channel.basicPublish(rabbitMqSettings.getExchangeName(), tpi.getFullTopicName(), properties, JSONObject.toJSONBytes(msg));
            if (callback != null) {
                callback.onSuccess(null);
            }
        } catch (IOException e) {
            log.error("Failed publish message: [{}].", msg, e);
            if (callback != null) {
                callback.onFailure(e);
            }
        }
    }

    public static void main(String[] args) {
        Map<String, String> map = Maps.newHashMap();
        map.put("data", "测试设备");
        TbMsg tbMsg = TbMsg.newMsg("Main", "POST_TELEMETRY_REQUEST", EntityIdFactory.getByTypeAndUuid(EntityType.RULE_CHAIN, UUID.randomUUID()), new TbMsgMetaData(map),
                "{\"data\": 22}", (RuleChainId) EntityIdFactory.getByTypeAndUuid(EntityType.RULE_CHAIN, UUID.fromString("51316c99-8bbf-407b-823a-b5648e6ca090")), null);

        RuleEngineQueueMsg build = new RuleEngineQueueMsg(null, null, null);
        ProtoQueueMsg<RuleEngineQueueMsg> ruleEngineQueueMsgProtoQueueMsg = new ProtoQueueMsg<>(tbMsg.getId(), build);
        byte[] bytes = JSONObject.toJSONBytes(ruleEngineQueueMsgProtoQueueMsg);
        System.out.println(new String(bytes));
        DefaultQueueMsg defaultQueueMsg = JSONObject.parseObject(new String(bytes), DefaultQueueMsg.class);
        System.out.println(new String(defaultQueueMsg.getData()));
    }

    @Override
    public void stop() {
        if (producerExecutor != null) {
            producerExecutor.shutdownNow();
        }
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException | TimeoutException e) {
                log.error("Failed to close the channel.");
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                log.error("Failed to close the connection.");
            }
        }
    }

    private void createTopicIfNotExist(TopicPartitionInfo tpi) {
        if (topics.contains(tpi)) {
            return;
        }
        admin.createTopicIfNotExists(tpi.getFullTopicName());
        topics.add(tpi);
    }
}
